# coding=utf-8
# 测试大乐透的中奖概率
# author: 给力星(www.powerxing.com)
import csv
import random
# 中奖红球，中奖篮球，我的红球，我的蓝球
def isWin(vol, wRed, wBlue, mRed, mBlue):
    if len(wRed) != 5 or len(wBlue) != 2 or len(mRed) != 5 or len(mBlue) != 2:
        print '出错!，位数不对！', vol, wRed, wBlue, mRed, mBlue, exit()
    R = len( wRed & mRed )
    B = len( wBlue & mBlue )
    if R == 5 and B == 2:
        return 1
    elif R == 5 and B == 1:
        return 2
    elif (R == 5) or (R == 4 and B == 2):
        return 3
    elif (R == 4 and B == 1) or (R == 3 and B == 2):
        return 4
    elif (R == 4) or (R == 3 and B == 1) or (R == 2 and B == 2): 
        return 5
    elif (R == 3) or (R == 2 and B == 1) or (R == 1 and B == 2) or (B == 2):
        return 6
    else:
        return 0

# 读取数据
csvfile = file('daletou.csv', 'rb')
reader = csv.reader(csvfile)
data = []
first_row = True
for line in reader:
    if first_row: # 过滤首行
        first_row = False
    else:
        vol = int(line[0])
        red = set()
        blue = set()
        for item in line[1:6]:
            red.add(int(item))
        for item in line[6:8]:
            blue.add(int(item))
        d = {
            'vol': vol,
            'red': red,
            'blue': blue
        }
        data.append(d)
data.reverse() # 按照从最早到最新的期数顺序
csvfile.close()
# 设置
N = 1000    # 设置迭代次数
prize = [0, 7923000, 131000, 4900, 200, 10, 5]  # 奖金，浮动奖金取最近15期的平均值
print '期数', len(data)
print '迭代次数', N
# 机选模式
result = [0]*7
for i in range(N):
    for item in data:
        vol = item['vol']
        wRed = item['red']
        wBlue = item['blue']
        # 每一期都机选一注彩票
        mRed = set(random.sample(range(1, 36), 5))
        mBlue = set(random.sample(range(1, 13), 2))
        w = isWin(vol, wRed, wBlue, mRed, mBlue)
        result[w] += 1
win_money = 0
for i in range(1, 7):
    win_money += result[i]*prize[i]
print '\n=== 机选模式 ==='
print '得奖次数', result
print '总花费', len(data)*2*N
print '总收益', win_money
# 追号模式
result = [0]*7
for i in range(N):
    # 每次迭代机选一注彩票作为守号
    mRed = set(random.sample(range(1, 36), 5))
    mBlue = set(random.sample(range(1, 13), 2))
    for item in data:
        vol = item['vol']
        wRed = item['red']
        wBlue = item['blue']
        w = isWin(vol, wRed, wBlue, mRed, mBlue)
        result[w] += 1
win_money = 0
for i in range(1, 7):
    win_money += result[i]*prize[i]
print '=== 追号模式 ==='
print '得奖次数', result
print '总花费', len(data)*2*N
print '总收益', win_money
print 'done!'
